#include "head.h"

int pipe_fd[2];
void func(int num) { write(pipe_fd[1], "1", 1); }

int main(int argc, char *argv[]) {
  pipe(pipe_fd);
  signal(SIGINT, func);

  // 启动子进程
  worker_status_t workerList[4]; // 按cpu线程数来定
  initPool(workerList, 4);

  // 初始化socket连接
  int socket_fd;
  initSocket(&socket_fd, "8080", "127.0.0.1");

  int epoll_fd = epoll_create1(0);
  // 放入监听:已完成三次握手的socket，还有与子进程进行通信的本地socket
  epollAddFd(epoll_fd, socket_fd);

  epollAddFd(epoll_fd, pipe_fd[0]);

  for (int i = 0; i < 4; i++) {
    epollAddFd(epoll_fd, workerList[i].local_socket);
  }

  while (1) {
    struct epoll_event events_ready[1024];
    memset(events_ready, 0, sizeof(events_ready));

    int epoll_num = epoll_wait(epoll_fd, events_ready, 1024, -1);

    for (int i = 0; i < epoll_num; i++) {
      int fd = events_ready[i].data.fd;

      if (fd == pipe_fd[0]) {
        char buffer[1];
        read(fd, buffer, sizeof(buffer));
        for (int j = 0; j < 4; j++) {
          sendMesg(workerList[j].local_socket, 1, -1);
        }
        for (int k = 0; k < 1; k++) {
          wait(NULL);
        }
        printf("all child processes are exited, main process exiting...\n");
        int flag, fdd;
        exit(0);
      } else if (fd == socket_fd) {
        int net_fd = accept(socket_fd, NULL, NULL);
        HandleConnect(workerList, 4, net_fd);
        close(net_fd);
        continue;
      } else {
        for (int k = 0; k < 4; k++) {
          if (workerList[k].local_socket == fd) {
            char uf[60] = {0};
            recv(fd, uf, sizeof(uf), 0);
            workerList[k].flag = FREE;
            break;
          }
        }
      }
    }
  }
  return 0;
}
